package com.lovo.user.mq;

import com.lovo.common.result.GlobalHandleException;
import com.lovo.common.result.ResultCode;
import com.lovo.common.util.MQUtil;
import com.lovo.common.util.RedisUtil;
import com.lovo.user.service.UserService;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
@RabbitListener(queues = "register.queue")
@Slf4j
public class RegisterReceiver {
    @Autowired
    private MQUtil mqUtil;
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private UserService userService;
    @RabbitHandler
    public void receive(Integer userId, Message message, Channel channel){
        try{
            String messageId = message.getMessageProperties().getMessageId();
            // 解决消费幂等性问题
            if(redisUtil.hasKey(messageId)){
                mqUtil.ack(message,channel);
                return;
            }
            redisUtil.set(messageId,userId,60 * 60);
            System.out.println("messageId:" + message.getMessageProperties().getMessageId());
            userService.sendEmail(userId);
            userService.sendPhone(userId);
//            int a = 10 / 0;
            mqUtil.ack(message,channel);
        }catch(Exception e){
            log.error("消费消息错误：" + e);
            mqUtil.nack(message,channel);
        }

    }
}
